<?php

namespace app\admin\model\facrm;

use think\Exception;
use think\Model;
use think\Queue;
use traits\model\SoftDelete;

class Flow extends Model
{
    use SoftDelete;
    // 表名
    protected $name = 'facrm_flow';
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'create_time';
    protected $updateTime = 'update_time';
    protected $deleteTime = 'delete_time';

    protected static function init()
		{
			self::afterInsert(function ($row) {
				//创建时自动添加权重值
				if (!$row->weigh){
					$pk = $row->getPk();
					$row->getQuery()->where($pk, $row[$pk])->update(['weigh' => $row[$pk]]);
				}

			});
			self::beforeWrite(function ($row) {
				$changedData = $row->getChangedData();

				//在更新之前对数组进行处理
				foreach ($row->getData() as $k => $value) {
					if (is_array($value) && is_array(reset($value))) {
						$value = json_encode(self::getArrayData($value), JSON_UNESCAPED_UNICODE);
					} else {
						$value = is_array($value) ? implode(',', $value) : $value;
					}
					$row->$k = $value;
				}
			});

		}
    public static function getArrayData($data)
    {
        if (!isset($data['value'])) {
            $result = [];
            foreach ($data as $index => $datum) {
                $result['field'][$index] = $datum['key'];
                $result['value'][$index] = $datum['value'];
            }
            $data = $result;
        }
        $fieldarr = $valuearr = [];
        $field = isset($data['field']) ? $data['field'] : (isset($data['key']) ? $data['key'] : []);
        $value = isset($data['value']) ? $data['value'] : [];
        foreach ($field as $m => $n) {
            if ($n != '') {
                $fieldarr[] = $field[$m];
                $valuearr[] = $value[$m];
            }
        }
        return $fieldarr ? array_combine($fieldarr, $valuearr) : [];
    }
    /**
     * 关联步骤
     * @return \think\model\relation\HasMany
     */
    public function step()
    {
        return $this->hasMany('\app\admin\model\facrm\flow\Step','flow_id','id');
    }
	/**
     * 获取审批模型string
     * @return string
     */
	public static function getModelStr($types){
		$model_str="";
        switch ($types){
           case 'receivables':
               $model_str='\app\admin\model\facrm\contract\Receivables';
               break;
            case "contract":
            case 'invoice':
                $model_str='\app\admin\model\facrm\\'.ucfirst($types);
                break;
            default:
                return false;

        }
		return $model_str;
	}
    /**
     * 添加待审批数据
     * @param $op_id 当前需要审批的ID
     * @param $admin_id 当前添加的管理员ID
     * @param string $types receivables contract 审批的类型
     * @param $flow_r 审批的数据可以为空
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function addFlow($op_id,$admin_id,$types,$flow_r){
        if (!$flow_r){
            $flow_r =self::getFlow($admin_id,$types);
        }
        if(!$model_str=self::getModelStr($types)){
			$this->error=__("审核类型有误");
            return false;
		}
        //处理收款审核流程
        $update_data = array();
        if ($flow_r) {
            $update_data['flow_id'] = $flow_r->id;
            if ($flow_r['config'] == 1) {
                //固定审批
                $flow_admin_id=$flow_r->step[0]['admin_ids'];
                if ($flow_r->step[0]['type']==1){
                    //上级领导审批
                    $Auth=new  \addons\facrm\library\Auth();
                    $parentIds= $Auth->getParentAdminIds($admin_id);
                    $flow_admin_id=$parentIds?join(',',$parentIds):$admin_id;//如果没有父类就是最高级的，同时也要审核一下
                }elseif ($flow_r->step[0]['type'] == 3){
                    //指定部门
					$auth=new  \addons\facrm\library\Auth();
					$groupIds=$auth->getGroupsAdminIds($flow_r->step[0]['admin_ids']);
                    $flow_admin_id=$groupIds?join(',',$groupIds):$admin_id;//如果没有父，同时自己也要审核一下
                }
                $update_data['step_id'] = $flow_r->step[0]['id'];
                $update_data['flow_admin_id'] = $flow_admin_id;

            }

        } else {
            //没有审批流程就默认是审批状态
            $update_data['check_status'] = 2;
        }
        $model=\model($model_str);
        $result=$model->where('id', $op_id)->update($update_data);
        //消息通知
        try {
            Queue::push("addons\\facrm\\library\\notice\queue\\Flow". ucfirst($types)."Job", ['model_id'=>$op_id,'data'=>$update_data]);
        }catch (Exception $e){

        }
        //消息通知end

        return $result;


    }

    /**
     * 获取第一级审批人ids
     * @param $flow_r
     * @param $admin_id
     * @return string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getAdminIds($flow_r,$admin_id){
        if ($flow_r->step&&isset($flow_r->step[0])){
            //固定审批
            $flow_admin_id=$flow_r->step[0]['admin_ids'];
            if ($flow_r->step[0]['type']==1){
                //上级领导审批
                $Auth=new  \addons\facrm\library\Auth();
                $parentIds= $Auth->getParentAdminIds($admin_id);
                $flow_admin_id=$parentIds?join(',',$parentIds):$admin_id;//如果没有父类就是最高级的，同时也要审核一下
            }
        }
       return $flow_admin_id;
    }
	
	 /**
     * 获取一条审批流信息
     */
    public static function getFlow($admin_id,$types){
        $model =new self();
		$auth=new  \addons\facrm\library\Auth();
        $groupIds=$auth->getGroupIds($admin_id);
        $flow_r =  $model->where('types', $types)->where("status", 1)->where(function($query) use ($groupIds){
            if ($groupIds){
                foreach ($groupIds as $k=>$v){
                    $query->whereOr("find_in_set({$v},group_ids)");
                }
            }
            $query->whereOr('group_ids','');
        })->order('weigh desc')->fetchSql(false)->find();
        return $flow_r;
    }
	
}